import Config from "../config/config";
import Aes from "./aes";
import Keys from "../config/keys";

export default class BaseApi{
    static HTTP_OK="1";
    http(success, complete = () => {wx.hideLoading()}, fail = () => { wx.showToast({title: '网络异常', icon: 'none', duration: 2000})}) {
        var decodeSuccess = (response) => {
            var temp = new Uint8Array(response.data);
            var rspStr = Aes.decode(temp);
            rspStr = JSON.parse(rspStr);
            // console.log(rspStr);
            if (rspStr.rspCode==BaseApi.HTTP_OK){
                success(rspStr.rspData);
            }else{
                //todo 这里没处理了
                console.log(rspStr);
            }
        };
        this._url((url) => {
            if (url){
                this._data((data) => {
                    // console.log(url);
                    // console.log(data);
                    data = Aes.encode(data);
                    var abf = new ArrayBuffer(data.length);
                    var array = new Uint8Array(abf);
                    for (var i=0;i<abf.byteLength;i++){
                        array[i] = data[i];
                    }
                    wx.request({
                        url: url,
                        data: abf,
                        method: this._method(),
                        responseType: this._responseType(),
                        header: {'content-type': 'text/plain;charset=utf-8'},
                        success: decodeSuccess,
                        fail: fail,
                        complete: complete
                    });
                });
            }else{
                this.notFindUrl();
            }
        });
    }

    /**
     * @param callback (str)=>{}
     */
    _url(callback) {
        var success = (res) => {
            if (res===undefined){
                callback();
            }else{
                if (res.data[this.constructor.name]) {
                    callback(res.data[this.constructor.name]);
                } else {
                    callback(res.data.coreservice[this.constructor.name]);
                }
            }
        };

        var storageFail = ()=>{
            this._downurl((url)=>{
                wx.request({//网络获取接口配置
                    url: url,
                    data: undefined,
                    method: "GET",
                    responseType: "text",
                    header: {'content-type': 'text/plain;charset=utf-8'},
                    success: (response)=>{
                        getApp().globalData.isDownHttpConfig = true;
                        wx.setStorage({//写入接口配置
                            key: Keys.downloadMainifest,
                            data: response.data,
                            success: () => {//写入成功记下时间
                                try {
                                    wx.setStorageSync(Keys.downloadMainifest_time, new Date().getTime().toString());
                                } catch (e) {
                                }
                            },
                            complete: () => {
                                success(response);
                            }
                        })
                    },
                    fail: ()=>{success()},
                });
            });
        };
        if (getApp()&&getApp().globalData.isDownHttpConfig){
            wx.getStorage({
                key: Keys.downloadMainifest,
                success: success,
                fail: storageFail
            });
        }else{
            storageFail();
        }
    }
    notFindUrl(){
        wx.showToast({title: '未找到接口：'+this.constructor.name, icon: 'none', duration: 2000});
    }

    //拼接获取接口配置的url
    _downurl(callback) {
        var arr = new Array();
        arr.push("http://config.jiankang51.cn/downloadMainifest?");
        arr.push("productId=");
        arr.push(Config.productId);
        arr.push("&pltId=");
        arr.push(Config.pltId);
        arr.push("&version=");
        arr.push(Config.version);
        wx.getStorage({
            key: Keys.downloadMainifest_time,
            success: (res) => {
                arr.push("&timestamp=");
                arr.push(res.data);
            },
            complete: () => {
                callback(arr.join(''));
            }
        });
    }

    _method() {
        return "POST";
    }
    /**
     * @param callback (data)=>{}
     */
    _data(callback) {
        if(this._method() === "GET"){
            callback();
        }else{
            var arr = new Array();
            arr.push("productId=");
            arr.push(Config.productId);
            arr.push("&pltId=");
            arr.push(Config.pltId);
            arr.push("&version=");
            arr.push(Config.version);
            arr.push("&sversion=");
            arr.push(Config.sversion);
            arr.push("&paramMethod=");
            arr.push(this.constructor.name);
            arr.push("&paramContent=");
            arr.push(JSON.stringify(this));
            callback(arr.join(''));
        }
    }

    _responseType() {
        return "arraybuffer";
    }
}

